package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("login")
    public String login(String userName, String pwd, HttpServletRequest req) {
        //调用业务方法得到结果
        UserBean user = service.login(userName, pwd);
        if (user != null) {
            req.getSession().setAttribute("loginUser", user);
            return "ok";
        }
        return "no";
    }

    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req) {
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");
        return user;
    }

    @RequestMapping("add")
    public String addUser(UserBean user) {
        boolean flag = service.addUser(user);
        if (flag) {
            return "ok";
        } else {
            return "no";
        }

    }

    @RequestMapping("findById")
    public UserBean findById(Integer userId) {
        return service.findById(userId);
    }

    @RequestMapping("findAll")
    public List<UserBean> findAll() {
        return service.findAll();
    }

    @RequestMapping("updatePwd")
    public String updatePwd(String oldPwd,Integer userId, String newPwd) {

       boolean flag= service.updatePwd(oldPwd,userId, newPwd);
       if (flag){
           return "ok";
       }else {
           return "no";
       }

    }

    @RequestMapping("updateGrade")
    public String updateGrade(Integer userId, String grade) {
        service.updateGrade(userId, grade);
        return "ok";
    }

    @RequestMapping("del")
    public String del(Integer userId, HttpServletRequest req) {
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");

        boolean flag = service.del(userId, user);
        if (flag) {
            return "ok";
        }
        return "no";
    }
}